/*常量*/
var CONSTANT = {
        DATA_TABLES : {
            DEFAULT_OPTION : { //DataTables初始化选项
                language: {
                    "sProcessing":   "处理中...",
                    "sLengthMenu":   "每页显示 _MENU_ 项",
                    "sZeroRecords":  "没有匹配结果",
                    "sInfo":         "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项。",
                    "sInfoEmpty":    "当前显示第 0 至 0 项，共 0 项",
                    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                    "sInfoPostFix":  "",
                    "sSearch":       "搜索:",
                    "sUrl":          "",
                    "sEmptyTable":     "表中数据为空",
                    "sLoadingRecords": "数据载入中...",
                    "sInfoThousands":  ",",
                    "oPaginate": {
                        "sFirst":    "首页",
                        "sPrevious": "上页",
                        "sNext":     "下页",
                        "sLast":     "末页",
                        "sJump":     "跳转"
                    },
                    "oAria": {
                        "sSortAscending":  ": 以升序排列此列",
                        "sSortDescending": ": 以降序排列此列"
                    }
                },
                autoWidth: false,   //禁用自动调整列宽
                stripeClasses: ["odd", "even"],//为奇偶行加上样式，兼容不支持CSS伪类的场合
                order: [],          //取消默认排序查询,否则复选框一列会出现小箭头
                processing: true,  //隐藏加载提示,自行处理
                serverSide: true,   //启用服务器端分页
                searching: false ,   //禁用原生搜索
                //scrollY: 450,		//垂直滚动     释放后全选功能失效
                //scrollX: true,       //水平滚动
            },
            COLUMN: {
                CHECKBOX: { //复选框单元格
                    className:"td-checkbox",
                    orderable: false,
                    data: null,
                    render: function (data, type, row, meta) {
                        return '<input type="checkbox" class="iCheck">';
                    },
            		width: "20px"
                }
            },
            RENDER: {   //常用render可以抽取出来，如日期时间、头像等
                ELLIPSIS: function (data, type, row, meta) {
                    data = data||"";
                    return '<span title="' + data + '">' + data + '</span>';
                },
                DATAFORMAT:function(data, type, row, meta){
                	if(data==null){
                		return '<span title=""></span>';
                	}
                	var mydate=new Date(data);
                	
                	formatDate=CONSTANT.FUNCTION.dateformat(mydate,'yyyy-MM-dd');
                	return '<span title="' + formatDate + '">' + formatDate + '</span>';
                }
            },
            
        },
        /*OVERALL:{
        	jsonData:new Array(),
        	code:""
        },*/
        PUBLICDATA:{},
        OVERALL:{
        	jsonData: new DefindMap(),
        	code:""
        },
        FUNCTION:{
        	deleteItem : function(selectedItems,url,_table) {
    	        var message;
    	        if (selectedItems&&selectedItems.length) {
    	            if (selectedItems.length == 1) {
    	                message = "确定要删除该条纪录吗?";
    	 
    	            }else{
    	                message = "确定要删除选中的"+selectedItems.length+"项记录吗?";
    	            }
    	            $.messager.confirm('Confirm',message,function(r){
    	                if (r){
    	                	var idParams=[];
    	                	for(var i=0;i<selectedItems.length;i++){
    	                		idParams[i]=selectedItems[i].id;
    	                	}
    	                	$.ajax({
    	                		url: url,
    	                    	type: "POST",
    	                    	cache : false,  //禁用缓存
    	                    	data:{
    	                    		idString:idParams.join(',')
    	                    	},
    	                        dataType: "json",
    	                    	success: function(res){
    	                    		if(res.status!='success'){
    	                    			$.messager.alert('提示','删除数据失败');
    	                    		}
    	                    		_table.draw();
    	                        }
    	                    });
    	                }
    	            });
    	        }else{
    	        	$.messager.alert('警告','请先选中要操作的行');
    	        }
    	    },
    	    deleteItemNoId : function(selectedItems,url,_table) {
    	        var message;
    	        if (selectedItems&&selectedItems.length) {
    	            if (selectedItems.length == 1) {
    	                message = "确定要删除该条纪录吗?";
    	 
    	            }else{
    	                message = "确定要删除选中的"+selectedItems.length+"项记录吗?";
    	            }
    	            $.messager.confirm('Confirm',message,function(r){
    	                if (r){
    	                	var idParams=[];
    	                	for(var i=0;i<selectedItems.length;i++){
    	                		idParams[i]=selectedItems[i];
    	                	}
    	                	$.ajax({
    	                		url: url,
    	                    	type: "POST",
    	                    	cache : false,  //禁用缓存
    	                    	data:{
    	                    		idString:idParams.join(',')
    	                    	},
    	                        dataType: "json",
    	                    	success: function(res){
    	                    		if(res.status!='success'){
    	                    			$.messager.alert('提示','删除数据失败');
    	                    		}
    	                    		_table.draw();
    	                        }
    	                    });
    	                }
    	            });
    	        }else{
    	        	$.messager.alert('警告','请先选中要操作的行');
    	        }
    	    },
    	    //列表翻译 数据获取
    	    chainData : function(code,data) {
    	    	var jsonData=new Array();
    	    	jsonData=CONSTANT.OVERALL.jsonData.get(code);
    	    	if(CONSTANT.OVERALL.code=="" || CONSTANT.OVERALL.code!=code){
    	    		if(jsonData == null){
        	    		$.ajax({
            	        	type: "POST",
            	        	url: "/XYL/syscode/getDateByCode",
            	        	cache : false,  //禁用缓存
            	            dataType: "json",
            	            async: false,
            	            //ifModified:true,//仅在服务器数据改变时获取新数据
            	            data:{
                        		code:code
                        	},
            	        	success: function(res){
            	        		CONSTANT.OVERALL.code=code;//设置当前code
            	        		CONSTANT.OVERALL.jsonData.set(code,res);
            	        		jsonData=CONSTANT.OVERALL.jsonData.get(code);
            	        		return CONSTANT.FUNCTION.chainHandle(jsonData,data);
            	            }
            	        });
        	    	}else{
        	    		return CONSTANT.FUNCTION.chainHandle(jsonData,data);
        	    	}
    	    	}else if(CONSTANT.OVERALL.code==code){
    	    		return CONSTANT.FUNCTION.chainHandle(jsonData,data);
    	    	}
    	    },
    	    //内容匹配
    	    chainHandle : function(jsonData,data) {
            	for(var i=0;i<jsonData.length;i++){
            		if(jsonData[i].typeCode==data){
            			return jsonData[i].typeName;
            		}else if(i==jsonData.length-1){
            			return null;
            		}
            	}
    	    },
    	    dateformat : function(mydate,format){
    	    	var date = {
    	                "M+": mydate.getMonth() + 1,
    	                "d+": mydate.getDate(),
    	                "h+": mydate.getHours(),
    	                "m+": mydate.getMinutes(),
    	                "s+": mydate.getSeconds(),
    	                "q+": Math.floor((mydate.getMonth() + 3) / 3),
    	                "S+": mydate.getMilliseconds()
    	         };
    	         if (/(y+)/i.test(format)) {
    	                format = format.replace(RegExp.$1, (mydate.getFullYear() + '').substr(4 - RegExp.$1.length));
    	         }
    	         for (var k in date) {
    	                if (new RegExp("(" + k + ")").test(format)) {
    	                       format = format.replace(RegExp.$1, RegExp.$1.length == 1
    	                              ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
    	                }
    	         }
    	         return format;
    	    },
    	    popuptextfun : function(itemText,listUrl,tableId,dialogDivId,fuzzySearchId,btnSearchId,btnSelectId,popupParam){
    	    	itemText = itemText.split(",")
    	    	var columns = new Array();
    	    	var param = {};
         		columns.push(CONSTANT.DATA_TABLES.COLUMN.CHECKBOX);
    	    	var deMap;
    	    	for(var i=0;i<itemText.length;i++){
    	    		deMap = {};
    	    		if(i==0){
        	    		deMap.visible = false;
    	    		}else{
        	    		deMap.visible = true;
    	    		}
    	    		deMap.className = "ellipsis";
    	    		deMap.data = itemText[i];
    	    		deMap.width = "100px";
    	    		deMap.render = CONSTANT.DATA_TABLES.RENDER.ELLIPSIS;
    	    		columns.push(deMap);
    	    	}
    	    	//console.debug(columns);
    	    	
    	    	var $table = $('#'+tableId);
    	        var _table = $table.dataTable($.extend(true,{},CONSTANT.DATA_TABLES.DEFAULT_OPTION, {
    	            ajax : function(data, callback, settings) {//ajax配置为function,手动调用异步查询
    	            	//var param = fitParams.getQueryCondition(data);
    	            	
    	            	var param = {};
    	    			//组装排序参数
    	    			if (data.order&&data.order.length&&data.order[0]) {
    	    				param.orderColumn=itemText[data.order[0].column-1];
    	    				param.orderDir = data.order[0].dir;
    	    			}
    	    			//组装查询参数
    	    			param.fuzzy = $("#"+fuzzySearchId).val();
    	    			if (param.fuzzy=="") {
    	    				param.fuzzySearch = false;
    	    			}else{
    	    				param.fuzzySearch = true;
    	    			}
    	    			//组装分页参数
    	    			param.currentItem = data.start;
    	    			param.pageSize = data.length;
    	    			param.draw = data.draw;
    	            	
    	                $.ajax({
    	                        type: "POST",
    	                        url: listUrl,
    	                        cache : false,  //禁用缓存
    	                        data: param,    //传入已封装的参数
    	                        dataType: "json",
    	                        success: function(result) {
    	                            //setTimeout仅为测试延迟效果
    	                            setTimeout(function(){
    	                                //异常判断与处理
    	                                if (result.errorCode) {
    	                                    $.messager.alert('提示信息', '查询失败。错误码：'+result.errorCode, 'warning');
    	                                    return;
    	                                }
    	     
    	                                var returnData = {};
    	                                returnData.draw = data.draw;
    	                                returnData.recordsTotal = result.recordsTotal;
    	                                returnData.recordsFiltered = result.recordsTotal;//后台不实现过滤功能，每次查询均视作全部结果
    	                                returnData.data = result.data;
    	                                
    	                                //console.debug(data);
    	                                //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
    	                                //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
    	                                callback(returnData);
    	                            },200);
    	                        },
    	                        error: function(XMLHttpRequest, textStatus, errorThrown) {
    	                            $.messager.alert('提示信息', '查询失败', 'warning');
    	                           // $wrapper.spinModal(false);
    	                        }
    	                    });
    	            },
    	            scrollX: "100%",
    	            "dom": 'tip',
    	            retrieve: true,
    	            columns:columns,
    	            "createdRow": function ( row, data, index ) {
    	            	//$('td', row).eq(4).css("display","none");
    	            },
    	            "drawCallback": function( settings ) {
    	                //渲染完毕后的回调
    	                //清空全选状态
    	               // $(":checkbox[name='cb-check-all']",$wrapper).prop('checked', false);
    	                //默认选中第一行
    	                $("tbody tr",$table).eq(0).click();
    	            }
    	        })).api();//此处需调用api()方法,否则返回的是JQuery对象而不是DataTables的API对象
    	       
    	        $('#'+dialogDivId).window({
    	            width:600,
    	            height:500,
    	            modal:true,
    	            minimizable:false,
    	            inline:false,
    	            onBeforeClose: function () {
    	            	$('#'+btnSelectId).unbind("click");
    	            	$('#'+btnSearchId).unbind("click");
    	            	$('#'+fuzzySearchId).val(null);
    	                //_table.destroy();
    	            }
    	        });
    	        //模糊查询事件
    	        $("#"+btnSearchId).click(function (){
    	        	_table.draw();
    	        });
    	      //选择事件
    	        $("#"+btnSelectId).click(function (){
    	        	var arrItemId = [];
    	            $("tbody :checkbox:checked",$table).each(function(i) {
    	            	var item = _table.row($(this).closest('tr')).data();
    	            	arrItemId.push(item);
    	            });
    	            if(arrItemId.length==1){
    	            	var popupParamArray=popupParam.split(",");
    	            	var properName;
    	            	var obj=arrItemId[0];
    	            	for(var i=0;i<popupParamArray.length;i++){
    	            		properName=popupParamArray[i].substring(popupParamArray[i].lastIndexOf('-')+1);
    	            		$("#"+popupParamArray[i]).val(obj[properName]);
    	            	}
    	            	$('#'+dialogDivId).window('close');
    	            }else{
    	            	$.messager.alert('提示信息', '请选择 一条信息', 'warning');
    	            }
    	            _table.destroy();
    	            $('#'+btnSelectId).unbind("click");
    	        	
    	        });
    	      
    	    },
    	    popupdeletetextfun : function(popupParam){
    	    	var popupParamArray=popupParam.split(",");
            	for(var i=0;i<popupParamArray.length;i++){
            		$("#"+popupParamArray[i]).val(null);
            	}
    	    },
    	    tableselectone : function($table,_table){
    	    	var arrItemId = [];
    	        $("tbody :checkbox:checked",$table).each(function(i) {
    	        	var item = _table.row($(this).closest('tr')).data();
    	        	arrItemId.push(item);
    	        });
    	    	if(arrItemId.length==1){ 
    	    		return arrItemId[0];
    	        }else{
    	        	$.messager.alert('提示信息', '请选择 一条信息', 'warning');
    	        	return null;
    	        }
    	    },
    	    //********************************************************
    	    popupdialogfun : function(itemText,listUrl,dialogDivId){
    	    	itemText = itemText.split(",")
    	    	var columns = new Array();
    	    	var param = {};
         		columns.push(CONSTANT.DATA_TABLES.COLUMN.CHECKBOX);
    	    	var deMap;
    	    	for(var i=0;i<itemText.length;i++){
    	    		deMap = {};
    	    		if(i==0){
        	    		deMap.visible = false;
    	    		}else{
        	    		deMap.visible = true;
    	    		}
    	    		deMap.className = "ellipsis";
    	    		deMap.data = itemText[i];
    	    		deMap.width = "80px";
    	    		deMap.render = CONSTANT.DATA_TABLES.RENDER.ELLIPSIS;
    	    		columns.push(deMap);
    	    	}
    	    	//console.debug(columns);
    	    	
    	    	var $table = $('div#'+dialogDivId+" table");
    	        var _table = $table.dataTable($.extend(true,{},CONSTANT.DATA_TABLES.DEFAULT_OPTION, {
    	            ajax : function(data, callback, settings) {//ajax配置为function,手动调用异步查询
    	            	//var param = fitParams.getQueryCondition(data);
    	            	
    	            	var param = {};
    	    			//组装排序参数
    	    			if (data.order&&data.order.length&&data.order[0]) {
    	    				param.orderColumn=itemText[data.order[0].column-1];
    	    				//console.debug(data.order[0]);
    	    				param.orderDir = data.order[0].dir;
    	    			}
    	    			//组装查询参数
    	    			param.fuzzy = $("#"+dialogDivId+" input").val();
    	    			if (param.fuzzy=="") {
    	    				param.fuzzySearch = false;
    	    			}else{
    	    				param.fuzzySearch = true;
    	    			}
    	    			//组装分页参数
    	    			param.currentItem = data.start;
    	    			param.pageSize = data.length;
    	    			param.draw = data.draw;
    	            	
    	                $.ajax({
    	                        type: "POST",
    	                        url: listUrl,
    	                        cache : false,  //禁用缓存
    	                        data: param,    //传入已封装的参数
    	                        dataType: "json",
    	                        success: function(result) {
    	                            //setTimeout仅为测试延迟效果
    	                            setTimeout(function(){
    	                                //异常判断与处理
    	                                if (result.errorCode) {
    	                                    $.messager.alert('提示信息', '查询失败。错误码：'+result.errorCode, 'warning');
    	                                    return;
    	                                }
    	     
    	                                var returnData = {};
    	                                returnData.draw = data.draw;
    	                                returnData.recordsTotal = result.recordsTotal;
    	                                returnData.recordsFiltered = result.recordsTotal;//后台不实现过滤功能，每次查询均视作全部结果
    	                                returnData.data = result.data;
    	                                
    	                                //console.debug(data);
    	                                //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
    	                                //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
    	                                callback(returnData);
    	                            },200);
    	                        },
    	                        error: function(XMLHttpRequest, textStatus, errorThrown) {
    	                            $.messager.alert('提示信息', '查询失败', 'warning');
    	                           // $wrapper.spinModal(false);
    	                        }
    	                    });
    	            },
    	            scrollX: "100%",
    	            dom: 'tip',
    	            destroy: true,
    	            retrieve: true,
    	            columns:columns,
    	            "createdRow": function ( row, data, index ) {
    	            	//$('td', row).eq(4).css("display","none");
    	            },
    	            "drawCallback": function( settings ) {
    	                //渲染完毕后的回调
    	                //清空全选状态
    	               // $(":checkbox[name='cb-check-all']",$wrapper).prop('checked', false);
    	                //默认选中第一行
    	                $("tbody tr",$table).eq(0).click();
    	            }
    	        })).api();//此处需调用api()方法,否则返回的是JQuery对象而不是DataTables的API对象
    	       
    	        $('#'+dialogDivId).window({
    	            width:600,
    	            height:500,
    	            modal:true,
    	            minimizable:false,
    	            inline:false,
    	            onBeforeClose: function () {
    	                $("#"+dialogDivId+" button").unbind("click");
    	                $("#"+dialogDivId+" input").val(null);
    	                _table.destroy();
    	            }
    	        });
    	        //模糊查询事件
    	        $("#"+dialogDivId+" button").click(function (){
    	        	_table.draw();
    	        });
    	        
    	      
    	    }
    	    
    	    
        }
	
};